package com.anlu.paypal.controller;

import com.anlu.paypal.common.ResponseData;
import com.anlu.paypal.service.PaymentV2Service;
import com.anlu.paypal.utils.PayPalClient;
import com.anlu.paypal.utils.PayPalRESTException;
import com.anlu.paypal.utils.RestResult;
import com.anlu.paypal.utils.URLUtils;
import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;
import javax.annotation.Resource;

@RestController
@Validated
@Slf4j
@RequestMapping(value = "/")
public class PaymentV2Controller {
    private Logger logger = LoggerFactory.getLogger(PaymentV2Controller.class);
    /**
     * 成功页面
     */
    public static final String PAYPAL_SUCCESS_URL = "paypalSuccess.html";

    /**
     * 取消页面
     */
    public static final String PAYPAL_CANCEL_URL = "pay/cancel";

    @Value("${paypal.web.url}")
    public  String payWebUrl ;

    @Value("${paypal.client.app}")
    public  String clientId ;

    @Value("${paypal.client.secret}")
    public  String secret ;

    @Value("${paypal.mode}")
    public  String mode ;

    @Resource
    private PaymentV2Service paymentV2Service;

    @PostMapping("/pay")
    public ResponseData payment(
            @RequestParam(value = "amount") String amount,
            @RequestParam(value = "currency",defaultValue = "USD") String currency,
            @RequestParam String productType,
            @RequestParam(value = "couponUsageId",required = false) String couponUsageId,
            HttpServletRequest request){
        //设置取消页面
        String cancelUrl =  URLUtils.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;
        //设置成功页面
        String successUrl = payWebUrl + PAYPAL_SUCCESS_URL;
        String sHtmlText = "";
        try {
            //订单表单
            sHtmlText = paymentV2Service.createPayment(amount, currency, cancelUrl, successUrl);
            //可根据需要 新增一条代付款记录(回调执行支付的时候 规避刷新页面重复扣费)
        } catch (PayPalRESTException e) {
            logger.error("创建订单表单异常:{}"+e.toString());
        }
        return ResponseData.ok(sHtmlText);
    }

    /**
     * 执行支付
     */
    @GetMapping(value = "pay/success")
    public ResponseData successPay(
            @RequestParam("token") String token) {
        //可以根据新增的付款记录规避重复扣费 参数新增orderId
        RestResult restResult = new RestResult();
        //捕获订单 进行支付
        HttpResponse<Order> response = null;
        OrdersCaptureRequest ordersCaptureRequest = new OrdersCaptureRequest(token);
        ordersCaptureRequest.requestBody(new OrderRequest());
        PayPalClient payPalClient = new PayPalClient();
        try {
            //环境判定sanbox 或 live
            response = payPalClient.client(mode, clientId, secret).execute(ordersCaptureRequest);
        } catch (IOException e) {
            logger.error("调用paypal扣款失败，失败原因 {}", e.getMessage());
        }
        for (PurchaseUnit purchaseUnit : response.result().purchaseUnits()) {
            for (Capture capture : purchaseUnit.payments().captures()) {
                if ("COMPLETED".equals(capture.status())) {
                    //支付成功
                    restResult.setMessage("支付成功");
                    return ResponseData.ok(restResult);
                }else{
                    //支付失败
                    restResult.setResultCode("0");
                    restResult.setMessage("支付失败");
                }
            }
        }
        restResult.setMessage("成功");
        return ResponseData.ok(restResult);
    }

}
